<template>
  <div class="container">
    <div class="ask-question-page">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1 class="page-title">提出问题</h1>
        <p class="page-description">提出一个清晰、详细的问题，更容易获得精准的回答。</p>
      </div>
      
      <!-- 提问表单 -->
      <div class="question-form-container">
        <el-form
          ref="questionFormRef"
          :model="questionForm"
          :rules="questionRules"
          label-position="top"
          @submit.prevent="submitQuestion"
          status-icon
        >
          <!-- 问题标题 -->
          <el-form-item label="问题标题" prop="title">
            <el-input
              v-model="questionForm.title"
              placeholder="用一句话描述您的问题"
              maxlength="100"
              show-word-limit
              clearable
              @input="autoSaveDraft"
            ></el-input>
            <div class="form-tip">标题应该简明扼要，避免使用"如何""怎么样"等词语开头</div>
          </el-form-item>
          
          <!-- 问题分类 -->
          <el-form-item label="问题分类" prop="categoryId">
            <el-select
              v-model="questionForm.categoryId"
              placeholder="选择问题的主要分类"
              class="category-select"
              filterable
              clearable
              @change="autoSaveDraft"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              ></el-option>
            </el-select>
          </el-form-item>
          
          <!-- 问题标签 -->
          <el-form-item label="标签" prop="tags">
            <el-select
              v-model="questionForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="添加最多5个标签"
              class="tags-select"
              collapse-tags
              collapse-tags-tooltip
              @change="autoSaveDraft"
            >
              <el-option
                v-for="tag in tagOptions"
                :key="tag"
                :label="tag"
                :value="tag"
              ></el-option>
            </el-select>
            <div class="form-tip">标签可以帮助更多相关领域的专家看到您的问题</div>
          </el-form-item>
          
          <!-- 问题详情 -->
          <el-form-item label="问题详情" prop="content">
            <div class="editor-wrapper">
              <!-- 使用文本域作为备选 -->
              <el-input 
                v-if="!mdEditorLoaded"
                v-model="questionForm.content" 
                type="textarea" 
                :rows="10"
                placeholder="详细描述您的问题，支持Markdown格式"
                @input="autoSaveDraft"
                @blur="validateContent"
              ></el-input>
              
              <!-- 使用Markdown编辑器组件 -->
              <MarkdownEditor
                v-else
                v-model="questionForm.content"
                @change="autoSaveDraft"
                @blur="validateContent"
                height="400px"
                placeholder="详细描述您的问题，支持Markdown格式"
                :theme="editorTheme"
                :autoFocus="true"
                :tabWidth="4"
                :noMermaid="false"
                :footers="['markdownTotal', 'scrollSync']"
              />
              <div class="form-tip">详细的问题描述有助于他人更好地理解并回答您的问题</div>
            </div>
          </el-form-item>
          
          <!-- 提交按钮 -->
          <el-form-item>
            <div class="form-actions">
              <span class="draft-saved-info" :class="{ 'visible': draftSaved }">
                <el-icon><Check /></el-icon> 草稿已保存
              </span>
              <div class="action-buttons">
                <el-button @click="cancelQuestion">取消</el-button>
                <el-button 
                  type="primary" 
                  :loading="submitting"
                  @click="submitQuestion"
                >发布问题</el-button>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 提问指南 -->
      <div class="ask-guidelines">
        <div class="guidelines-card">
          <h3 class="guidelines-title">
            <el-icon><InfoFilled /></el-icon> 如何提出好问题
          </h3>
          <ul class="guidelines-list">
            <li>确保问题标题清晰具体，避免太宽泛</li>
            <li>详细描述问题背景和您已尝试的解决方案</li>
            <li>添加相关代码或错误信息（如适用）</li>
            <li>检查是否有类似问题已被回答</li>
            <li>选择合适的标签以便专业人士发现</li>
          </ul>
        </div>
        
        <div class="guidelines-card">
          <h3 class="guidelines-title">
            <el-icon class="warning-icon"><WarningFilled /></el-icon> 避免的问题
          </h3>
          <ul class="guidelines-list">
            <li>重复已存在的问题</li>
            <li>包含侮辱、歧视或不当内容</li>
            <li>发布与社区主题无关的内容</li>
            <li>发布推广或广告内容</li>
            <li>提交没有实际内容的空泛问题</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useQuestionStore } from '../stores/question'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, InfoFilled, WarningFilled } from '@element-plus/icons-vue'
import { getVisibleCategories } from '../api/category' // 导入分类API
import MarkdownEditor from '../components/MarkdownEditor.vue' // 导入自定义Markdown编辑器组件

const router = useRouter()
const questionStore = useQuestionStore()
const userStore = useUserStore()
const submitting = ref(false)
const questionFormRef = ref(null)
const draftSaved = ref(false)
const draftSaveTimer = ref(null)
const draftAutoSaveInterval = ref(null)
const editorTheme = ref('light') // 编辑器主题，可以是 'light' 或 'dark'
const mdEditorLoaded = ref(false) // 标记编辑器是否已加载

// 在组件mounted时执行初始化逻辑
onMounted(async () => {
  // 检查用户是否登录
  if (!userStore.isLogin) {
    ElMessage.warning('请先登录后再提问')
    router.push('/login?redirect=/ask')
    return
  }
  
  // 尝试加载草稿
  loadDraft()
  
  // 设置定时自动保存
  draftAutoSaveInterval.value = setInterval(() => {
    if (hasFormContent.value) {
      saveDraft()
    }
  }, 60000) // 每分钟自动保存一次
  
  // 获取分类数据
  await fetchCategories()
  
  // 延迟加载编辑器
  nextTick(() => {
    setTimeout(() => {
      mdEditorLoaded.value = true
    }, 500) // 延迟500ms确保组件正确加载
  })
})

// 在组件销毁前保存草稿并清除计时器
onBeforeUnmount(() => {
  if (draftSaveTimer.value) {
    clearTimeout(draftSaveTimer.value)
  }
  
  if (draftAutoSaveInterval.value) {
    clearInterval(draftAutoSaveInterval.value)
  }
  
  if (hasFormContent.value) {
    saveDraft()
  }
})

// 问题表单
const questionForm = reactive({
  title: '',
  categoryId: '',
  tags: [],
  content: ''
})

// 检查表单是否有内容需要保存
const hasFormContent = computed(() => {
  return questionForm.title.trim() !== '' || 
         questionForm.content.trim() !== '' || 
         questionForm.tags.length > 0 || 
         questionForm.categoryId !== ''
})

// 表单验证规则
const questionRules = {
  title: [
    { required: true, message: '请输入问题标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度应在1到100个字符之间', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        const commonPrefixes = ['如何', '怎么', '怎样', '请问', '有谁知道'];
        let hasPrefix = false;
        
        for (const prefix of commonPrefixes) {
          if (value.startsWith(prefix)) {
            hasPrefix = true;
            break;
          }
        }
        
        if (hasPrefix) {
          callback(new Error('建议直接描述问题核心，无需使用"如何"、"怎么"等开头'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  categoryId: [
    { required: true, message: '请选择问题分类', trigger: 'change' }
  ],
  tags: [
    { required: true, message: '请至少添加一个标签', trigger: 'change' },
    { 
      validator: (rule, value, callback) => {
        if (value.length > 5) {
          callback(new Error('标签最多只能添加5个'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    },
    {
      validator: (rule, value, callback) => {
        // 检查标签长度
        for (const tag of value) {
          if (tag.length > 20) {
            callback(new Error('单个标签长度不能超过20个字符'));
            return;
          } else if (tag.length < 2) {
            callback(new Error('单个标签长度不能少于2个字符'));
            return;
          }
        }
        callback();
      },
      trigger: 'change'
    }
  ],
  content: [
    { required: true, message: '请输入问题详情', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        // 纯文本内容长度检查，移除 Markdown 标记
        const plainText = value.replace(/\!\[.*?\]\(.*?\)/g, '[图片]') // 替换图片
                              .replace(/\[.*?\]\(.*?\)/g, '[链接]')     // 替换链接
                              .replace(/```[\s\S]*?```/g, '[代码块]')   // 替换代码块
                              .replace(/`.*?`/g, '[代码]')              // 替换行内代码
                              .replace(/\*\*(.*?)\*\*/g, '$1')          // 替换粗体
                              .replace(/\*(.*?)\*/g, '$1')              // 替换斜体
                              .replace(/^#+\s+/gm, '')                  // 替换标题
                              .replace(/^\s*[*-]\s+/gm, '')             // 替换无序列表
                              .replace(/^\s*\d+\.\s+/gm, '')            // 替换有序列表
                              .trim();
                              
        if (plainText.length < 5) {
          callback(new Error('问题详情内容过短，请提供更多细节（至少5个字符）'));
        } else if (plainText.length > 20000) {
          callback(new Error('问题详情内容过长，请精简描述（不超过20000个字符）'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
}

// 手动验证内容编辑器
const validateContent = () => {
  if (questionFormRef.value) {
    // 添加延迟以确保内容已同步
    setTimeout(() => {
      questionFormRef.value.validateField('content')
    }, 100)
  }
}

// 获取分类列表
const categories = ref([])
const fetchCategories = async () => {
  try {
    // 调用分类API，获取可见分类
    const res = await getVisibleCategories()
    if (res.code === 200 && res.data) {
      categories.value = res.data
    } else {
      // 使用默认分类数据
      useDefaultCategories()
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败，使用默认数据')
    useDefaultCategories()
  }
}

// 使用默认分类数据
const useDefaultCategories = () => {
  categories.value = [
    { id: 1, name: '编程开发' },
    { id: 2, name: '数据科学' },
    { id: 3, name: '人工智能' },
    { id: 4, name: '网络安全' },
    { id: 5, name: '前端技术' },
    { id: 6, name: '后端技术' },
    { id: 7, name: '移动开发' },
    { id: 8, name: '运维部署' },
    { id: 9, name: '数据库' },
    { id: 10, name: '其他技术' }
  ]
}

// 获取标签建议 - 使用静态数据
const tagOptions = ref([
  'JavaScript', 'Python', 'Java', 'C++', 'PHP',
  'React', 'Vue', 'Angular', 'Node.js', 'Express',
  'Spring', 'Django', 'Flask', 'Laravel', 'MySQL',
  'MongoDB', 'Redis', 'Docker', 'Kubernetes', 'Git',
  'Linux', 'AWS', 'Azure', 'TensorFlow', 'PyTorch'
]);

// 自动保存草稿
const autoSaveDraft = () => {
  draftSaved.value = false
  
  if (draftSaveTimer.value) {
    clearTimeout(draftSaveTimer.value)
  }
  
  draftSaveTimer.value = setTimeout(() => {
    saveDraft()
  }, 2000)
}

// 保存草稿
const saveDraft = () => {
  // 只有当表单有内容时才保存草稿
  if (hasFormContent.value) {
    localStorage.setItem('question_draft', JSON.stringify({
      title: questionForm.title,
      categoryId: questionForm.categoryId,
      tags: questionForm.tags,
      content: questionForm.content,
      timestamp: new Date().getTime()
    }))
    draftSaved.value = true
    
    // 3秒后隐藏保存提示
    setTimeout(() => {
      draftSaved.value = false
    }, 3000)
  }
}

// 加载草稿
const loadDraft = () => {
  try {
    const draftData = localStorage.getItem('question_draft')
    if (draftData) {
      const draft = JSON.parse(draftData)
      
      // 检查草稿是否在24小时内
      const now = new Date().getTime()
      const draftTime = draft.timestamp || 0
      const hoursDiff = (now - draftTime) / (1000 * 60 * 60)
      
      if (hoursDiff < 24) {
        ElMessageBox.confirm(
          '检测到您有未发布的问题草稿，是否恢复?', 
          '恢复草稿', 
          {
            confirmButtonText: '恢复',
            cancelButtonText: '不需要',
            type: 'info'
          }
        ).then(() => {
          questionForm.title = draft.title || ''
          questionForm.categoryId = draft.categoryId || ''
          questionForm.tags = draft.tags || []
          questionForm.content = draft.content || ''
          draftSaved.value = true
          
          // 恢复后显示一下保存状态
          setTimeout(() => {
            draftSaved.value = false
          }, 3000)
        }).catch(() => {
          // 用户选择不恢复，清除草稿
          localStorage.removeItem('question_draft')
        })
      } else {
        // 草稿太旧，自动清除
        localStorage.removeItem('question_draft')
      }
    }
  } catch (error) {
    console.error('加载草稿失败:', error)
  }
}

// 提交问题
const submitQuestion = async () => {
  if (!questionFormRef.value) return
  
  try {
    // 先进行表单验证
    await questionFormRef.value.validate()
    
    submitting.value = true
    
    // 格式化标签数据
    const formattedTags = questionForm.tags.join(',')
    
    // 构建请求数据
    const requestData = {
      title: questionForm.title.trim(),
      categoryId: questionForm.categoryId,
      tags: formattedTags,
      content: questionForm.content.trim()
    }
    
    // 调用提交问题的API
    const result = await questionStore.createQuestion(requestData)
    
    // 检查API响应
    if (!result || result.code !== 200) {
      throw new Error(result?.message || '提交失败')
    }
    
    // 提交成功后清除草稿
    localStorage.removeItem('question_draft')
    
    ElMessage.success('问题发布成功！')
    
    // 跳转到问题详情页
    if (result.data && result.data.id) {
      router.push(`/questions/${result.data.id}`)
    } else {
      // 如果没有返回ID，则跳转到首页
      router.push('/home')
    }
  } catch (error) {
    console.error('提交问题失败:', error)
    
    if (error.message) {
      ElMessage.error(`提交失败: ${error.message}`)
    } else {
      ElMessage.error('提交问题失败，请检查表单内容')
    }
    
    // 滚动到第一个错误的表单项
    nextTick(() => {
      const errorField = document.querySelector('.el-form-item.is-error')
      if (errorField) {
        errorField.scrollIntoView({ behavior: 'smooth', block: 'center' })
      }
    })
  } finally {
    submitting.value = false
  }
}

// 取消提问
const cancelQuestion = () => {
  // 弹出确认对话框
  if (hasFormContent.value) {
    ElMessageBox.confirm(
      '确定要放弃当前编辑的问题吗？草稿将会保留24小时', 
      '确认离开', 
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      saveDraft() // 保存最后草稿
      router.push('/home')
    }).catch(() => {
      // 用户取消，不做操作
    })
  } else {
    router.push('/home')
  }
}
</script>

<style scoped>
.ask-question-page {
  padding: 20px 0 40px;
}

.page-header {
  margin-bottom: 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  padding: 32px 24px;
  border-radius: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #1e293b;
  margin: 0 0 12px;
}

.page-description {
  color: #64748b;
  font-size: 16px;
  margin: 0;
}

.question-form-container {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 32px;
  margin-bottom: 32px;
}

.form-tip {
  color: #94a3b8;
  font-size: 13px;
  margin-top: 6px;
}

.category-select,
.tags-select {
  width: 100%;
}

.editor-wrapper {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 已移除自定义富文本编辑器样式，现在使用MarkdownEditor组件 */

.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 24px;
  border-top: 1px solid #e2e8f0;
  padding-top: 24px;
}

.action-buttons {
  display: flex;
  gap: 16px;
}

.draft-saved-info {
  display: flex;
  align-items: center;
  color: #10b981;
  font-size: 14px;
  background-color: rgba(16, 185, 129, 0.1);
  padding: 6px 12px;
  border-radius: 6px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.draft-saved-info.visible {
  opacity: 1;
}

.draft-saved-info .el-icon {
  margin-right: 4px;
  font-size: 16px;
}

/* 提问指南 */
.ask-guidelines {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.guidelines-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 24px;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.guidelines-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.guidelines-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 16px;
}

.guidelines-title .el-icon {
  margin-right: 10px;
  color: var(--el-color-primary);
  font-size: 20px;
}

.guidelines-title .warning-icon {
  color: var(--el-color-warning);
}

.guidelines-list {
  margin: 0;
  padding-left: 20px;
}

.guidelines-list li {
  margin-bottom: 10px;
  color: #64748b;
  line-height: 1.5;
  position: relative;
}

.guidelines-list li:last-child {
  margin-bottom: 0;
}

.guidelines-list li::before {
  content: '';
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: var(--el-color-primary);
  position: absolute;
  left: -16px;
  top: 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .ask-guidelines {
    grid-template-columns: 1fr;
  }
  
  .question-form-container {
    padding: 24px 16px;
  }
  
  .form-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: flex-end;
  }
  
  .draft-saved-info {
    margin-bottom: 8px;
  }
  
  .page-header {
    text-align: center;
    padding: 24px 16px;
  }
}

@media (max-width: 480px) {
  .action-buttons {
    width: 100%;
    justify-content: space-between;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .page-description {
    font-size: 14px;
  }
}
</style> 